//
//  ST_RecommendPecVideoController.swift
//  btvideo
//
//  Created by mac on 2020/6/8.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON
import SwifterSwift


class ST_RecommendPecVideoController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         
        
        self.view.backgroundColor = .black
        
        
        self.view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        self.view.addSubview(close_feed_back_btn)
        
        close_feed_back_btn.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize.init(width: 44, height: 44))
            make.right.equalToSuperview().offset(-15+7)
            make.top.equalToSuperview().offset(statusBarHeight)
        }
        
        view.addSubview(comment_input_mask_view)
        comment_input_mask_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(comment_input_bar)
        comment_input_bar.snp.makeConstraints { (make) in
            make.height.equalTo(ST_CommentInputBar.height)
            make.bottom.left.right.equalToSuperview()
        }
        
        ST_RecommendVideoDataAdapter.shared.video_detail_delegate = self
      
        NotificationCenter.default.addObserver(self, selector: #selector(goback_topmost_controller_handle(noti:)), name: Notification.Name.goback_topmost_controller, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(present_to_controller_handle(noti:)), name: Notification.Name.global_present_controller, object: nil)
          
    }
    deinit {
        
//        print("播放视频 开始 释放")
        
        NotificationCenter.default.removeObserver(self)
    }

//    MARK: - Notification Observer
    @objc fileprivate func present_to_controller_handle(noti:Notification){
        
        if let toController = noti.userInfo?["toController"] as? UIViewController{
            
            if toController is ST_DarkST_CommentListViewController{
                return
            }
            self.current_play_cell?.pause_video()
        }
    }
    
    @objc fileprivate func goback_topmost_controller_handle(noti:Notification){
        
        if let toController = noti.userInfo?["controller"] as? UIViewController{
           
            print("试试呢：",toController)
            
            if toController == self{
                
                self.current_play_cell?.continuePlay()
            }
        }
        
    }
    
    
    //    MARK: - Properties
    fileprivate var current_play_cell:ST_RecommendPecVideoCell?
    
    var normalIdx = 0{
        didSet{
            
            UIView.animate(withDuration: 0, animations: {
                
                self.collectionView.setContentOffset(CGPoint.init(x: 0, y: ScreenHeight*self.normalIdx.cgFloat), animated: false)
                
            }, completion: { _ in
                
                self.stoppedScrolling()
            })
        }
    }
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.scrollDirection = .vertical
        controlLayout.minimumLineSpacing = 0
        controlLayout.minimumInteritemSpacing = 0
        controlLayout.itemSize = CGSize.init(width: ScreenWidth, height: ScreenHeight)
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_RecommendPecVideoCell.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.isPagingEnabled = true
        control.backgroundColor = Color.black
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        //        control.backgroundColor = Color.random
        
        //       control.alwaysBounceVertical = true
        
        return control
    }()
    
    fileprivate lazy var close_feed_back_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("特质_icon_关闭")!)
        control.addTarget(self, action: #selector(closeBackHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var comment_input_bar:ST_CommentInputBar = {
       let control = ST_CommentInputBar()
        control.endEditClosure = {[weak self] str,replyId,commentId in
            
            self?.end_edit_comment_handle()
            
            self?.send_message_handle(comment: str, replyUserId: replyId, commentId: commentId)
        }
        control.keyBroadHiddenClosure = {[weak self]  in
            self?.hidden_mask_view(hidden: true)
        }
        control.keyBroadShowClosure = {[weak self]  in
            self?.hidden_mask_view(hidden: false)
        }
        
        if FACE_AVATAE_STATE != 3{
            control.onlyInputEmoji = true
        }
        return control
    }()
    
    fileprivate lazy var comment_input_mask_view:UIView = {
       let control = UIView()
        control.alpha = 0
        control.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(end_edit_comment_handle))
        control.addGestureRecognizer(tap)
        return control
    }()
   
}

extension ST_RecommendPecVideoController{
    
    @objc fileprivate func closeBackHandle(){
        
        self.stopPlayVideo()
        
        goback_previous_controller()
        
    }
}

extension ST_RecommendPecVideoController:ST_PinterestHomeDataAdapterViewDelegate{
    
    func reload_view_from_data_adapter(currentCount:Int){
        
        if currentCount < 1{
            return
        }
        
        
        if ST_RecommendVideoDataAdapter.shared.currentPage > 1{
            
            let maxIdx = ST_RecommendVideoDataAdapter.shared.data_array.count - 1
            
            let minIdx = maxIdx - currentCount + 1
            
            let willInsertSet = Array(minIdx...maxIdx).map { (i) -> IndexPath in
                return IndexPath.init(row: i, section: 0)
            }
            
            self.collectionView.performBatchUpdates({
                
                   self.collectionView.insertItems(at: willInsertSet)
                
               }, completion:nil)
            
        }else{
            
            self.pause_video()
            
            self.collectionView.reloadData()
        }
        
    }
    
    func fail_load_data(code: Int, error: String) {
        
        self.collectionView.reloadData()
    }
    
    
    func refreshCell(groupId: String) {
        
        if self.current_play_cell?.child_model?.group_id.string == groupId{
            
            self.current_play_cell?.refresh_other_data()
        }
        
        
    }
    
}


//MARK:- UICollectionViewDelegate
extension ST_RecommendPecVideoController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return ST_RecommendVideoDataAdapter.shared.data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        
        if ST_RecommendVideoDataAdapter.shared.data_array[safe:indexPath.row]?.group_id == self.current_play_cell?.child_model?.group_id{
            
            self.current_play_cell?.stopVideo()
            
            self.current_play_cell = nil
        }
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_RecommendPecVideoCell.self, for: indexPath)
        
        cell.child_model = ST_RecommendVideoDataAdapter.shared.data_array[indexPath.row]
        
        cell.beginInput = {[weak self] type,groupId in
            
            if type == 2 || FACE_AVATAE_STATE != 3{
                
                self?.comment_input_bar.onlyInputEmoji = true
            }else{
                self?.comment_input_bar.onlyInputEmoji = false
            }
            
            self?.comment_input_bar.groupId = groupId
            self?.comment_input_bar.startEdit()
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if scrollView.contentSize.height - ScreenHeight - scrollView.contentOffset.y <  ScreenHeight * 2{
            
            ST_RecommendVideoDataAdapter.shared.load_data_from_remote()
        }
        
    }
    
    func stoppedScrolling()  {
        
        let row = self.collectionView.contentOffset.y/ScreenHeight
        
        print("滑动 停止 监听----播放IndexPath:",row)
        
        self.play(indexPath: IndexPath.init(row: row.int, section: 0))
        
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        stoppedScrolling()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        if !decelerate{
            stoppedScrolling()
        }
        
    }
}

//    MARK:- Play Operation
extension ST_RecommendPecVideoController{
    
    
    
    fileprivate func play(indexPath:IndexPath){
      
        guard let cell = collectionView.cellForItem(at: indexPath) as? ST_RecommendPecVideoCell ,cell != self.current_play_cell else{return}
        
        
        cell.play()
        
        self.current_play_cell?.stopVideo()
        
        self.current_play_cell = cell
    }
    
    func stopPlayVideo(){
        
        self.current_play_cell?.stopVideo()
        
        self.current_play_cell = nil
    }
    
    
    func continuePlayVideo(){
        
        self.current_play_cell?.continuePlay()
        
    }
    
    func pause_video(){
        
        self.current_play_cell?.pause_video()
        
    }
    
}



//MARK: - Comment Input Event
extension ST_RecommendPecVideoController{
    
    @objc fileprivate func end_edit_comment_handle(){
        
        comment_input_bar.endEditing(true)
        
        
    }
    
    func hidden_mask_view(hidden:Bool){

        UIView.animate(withDuration: 0.25, animations: {
            
            self.comment_input_mask_view.alpha = hidden ? 0 : 1
            
        }) { (f) in
            
        }
        
    }
    
    fileprivate func send_message_handle(comment:String,replyUserId:String?,commentId:String?){
        
        guard let gId = self.comment_input_bar.groupId else{
            return
        }
        
        let firstModel = ST_RecommendVideoDataAdapter.shared.data_array.first { (cellModel) -> Bool in
            return cellModel.group_id.string == gId
        }
        
        guard let currModel = firstModel else { return  }
        

        //        只能发表情，但是没有检测到表情
        if currModel.commentType == 2 && comment.containEmoji == false{
            
            self.toast(text: "该特质只支持emoji评论")
            
            return
        }
        
        self.insertLocalDanmaku(comment: comment,groupId: currModel.group_id.string)
        
        let param = ["target_accid":currModel.accid,"feature_id":currModel.feature_id,"group_id":currModel.group_id,"type":currModel.commentType,"comment":comment] as [String : Any]
        
        
        
        
        ST_BTGlobalDataCenter.shared.commentPeculiarityEvent(peculiarity_id: currModel.group_id.string, commented_user_id: currModel.accid)
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
                    return
                }
        
        if restrictFemaleFace(){
            return
        }
        
        if ST_BTUserInfoManager.shared.confined_to_ticket(){
                
                let vc = ST_TicketViewController()
                
                vc.from = .mainIndexConfined
                
                GlobalPresent(toController: vc)
                
                return
            }
        
        JVrequest(PH.sendCommentApi,parameters: param, success: { (json) in
            
        }) { (code, err) in
            self.toast(text: err)
        }
        
    }
    
    
    func insertLocalDanmaku(comment:String,groupId:String) {
        
        guard let idx = ST_RecommendVideoDataAdapter.shared.data_array.firstIndex(where: { (cellModel) -> Bool in
            return cellModel.group_id.string == groupId
        }) else { return  }
        
        
        
        if let cell = collectionView.cellForItem(at: IndexPath.init(row: Int(idx.uInt), section: 0)) as? ST_RecommendPecVideoCell{
            
            cell.insert_barrage(content: comment)
        }
        
    }
    
    
    
    
}
